home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / ruby / 1.8 / pathname.rb < prev    next >
Encoding:
Ruby Source  |  2010-06-16  |  29.2 KB  |  1,077 lines

  1. #
  2. # = pathname.rb
  3. #
  4. # Object-Oriented Pathname Class
  5. #
  6. # Author:: Tanaka Akira <akr@m17n.org>
  7. # Documentation:: Author and Gavin Sinclair
  8. #
  9. # For documentation, see class Pathname.
  10. #
  11. # <tt>pathname.rb</tt> is distributed with Ruby since 1.8.0.
  12. #
  13.  
  14. #
  15. # == Pathname
  16. #
  17. # Pathname represents a pathname which locates a file in a filesystem.
  18. # The pathname depends on OS: Unix, Windows, etc.
  19. # Pathname library works with pathnames of local OS.
  20. # However non-Unix pathnames are supported experimentally.
  21. #
  22. # It does not represent the file itself.
  23. # A Pathname can be relative or absolute.  It's not until you try to
  24. # reference the file that it even matters whether the file exists or not.
  25. #
  26. # Pathname is immutable.  It has no method for destructive update.
  27. #
  28. # The value of this class is to manipulate file path information in a neater
  29. # way than standard Ruby provides.  The examples below demonstrate the
  30. # difference.  *All* functionality from File, FileTest, and some from Dir and
  31. # FileUtils is included, in an unsurprising way.  It is essentially a facade for
  32. # all of these, and more.
  33. #
  34. # == Examples
  35. #
  36. # === Example 1: Using Pathname
  37. #
  38. #   require 'pathname'
  39. #   p = Pathname.new("/usr/bin/ruby")
  40. #   size = p.size              # 27662
  41. #   isdir = p.directory?       # false
  42. #   dir  = p.dirname           # Pathname:/usr/bin
  43. #   base = p.basename          # Pathname:ruby
  44. #   dir, base = p.split        # [Pathname:/usr/bin, Pathname:ruby]
  45. #   data = p.read
  46. #   p.open { |f| _ } 
  47. #   p.each_line { |line| _ }
  48. #
  49. # === Example 2: Using standard Ruby
  50. #
  51. #   p = "/usr/bin/ruby"
  52. #   size = File.size(p)        # 27662
  53. #   isdir = File.directory?(p) # false
  54. #   dir  = File.dirname(p)     # "/usr/bin"
  55. #   base = File.basename(p)    # "ruby"
  56. #   dir, base = File.split(p)  # ["/usr/bin", "ruby"]
  57. #   data = File.read(p)
  58. #   File.open(p) { |f| _ } 
  59. #   File.foreach(p) { |line| _ }
  60. #
  61. # === Example 3: Special features
  62. #
  63. #   p1 = Pathname.new("/usr/lib")   # Pathname:/usr/lib
  64. #   p2 = p1 + "ruby/1.8"            # Pathname:/usr/lib/ruby/1.8
  65. #   p3 = p1.parent                  # Pathname:/usr
  66. #   p4 = p2.relative_path_from(p3)  # Pathname:lib/ruby/1.8
  67. #   pwd = Pathname.pwd              # Pathname:/home/gavin
  68. #   pwd.absolute?                   # true
  69. #   p5 = Pathname.new "."           # Pathname:.
  70. #   p5 = p5 + "music/../articles"   # Pathname:music/../articles
  71. #   p5.cleanpath                    # Pathname:articles
  72. #   p5.realpath                     # Pathname:/home/gavin/articles
  73. #   p5.children                     # [Pathname:/home/gavin/articles/linux, ...]
  74. # == Breakdown of functionality
  75. #
  76. # === Core methods
  77. #
  78. # These methods are effectively manipulating a String, because that's all a path
  79. # is.  Except for #mountpoint?, #children, and #realpath, they don't access the
  80. # filesystem.
  81. #
  82. # - +
  83. # - #join
  84. # - #parent
  85. # - #root?
  86. # - #absolute?
  87. # - #relative?
  88. # - #relative_path_from
  89. # - #each_filename
  90. # - #cleanpath
  91. # - #realpath
  92. # - #children
  93. # - #mountpoint?
  94. #
  95. # === File status predicate methods
  96. #
  97. # These methods are a facade for FileTest:
  98. # - #blockdev?
  99. # - #chardev?
  100. # - #directory?
  101. # - #executable?
  102. # - #executable_real?
  103. # - #exist?
  104. # - #file?
  105. # - #grpowned?
  106. # - #owned?
  107. # - #pipe?
  108. # - #readable?
  109. # - #world_readable?
  110. # - #readable_real?
  111. # - #setgid?
  112. # - #setuid?
  113. # - #size
  114. # - #size?
  115. # - #socket?
  116. # - #sticky?
  117. # - #symlink?
  118. # - #writable?
  119. # - #world_writable?
  120. # - #writable_real?
  121. # - #zero?
  122. #
  123. # === File property and manipulation methods
  124. #
  125. # These methods are a facade for File:
  126. # - #atime
  127. # - #ctime
  128. # - #mtime
  129. # - #chmod(mode)
  130. # - #lchmod(mode)
  131. # - #chown(owner, group)
  132. # - #lchown(owner, group)
  133. # - #fnmatch(pattern, *args)
  134. # - #fnmatch?(pattern, *args)
  135. # - #ftype
  136. # - #make_link(old)
  137. # - #open(*args, &block)
  138. # - #readlink
  139. # - #rename(to)
  140. # - #stat
  141. # - #lstat
  142. # - #make_symlink(old)
  143. # - #truncate(length)
  144. # - #utime(atime, mtime)
  145. # - #basename(*args)
  146. # - #dirname
  147. # - #extname
  148. # - #expand_path(*args)
  149. # - #split
  150. #
  151. # === Directory methods
  152. #
  153. # These methods are a facade for Dir:
  154. # - Pathname.glob(*args)
  155. # - Pathname.getwd / Pathname.pwd
  156. # - #rmdir
  157. # - #entries
  158. # - #each_entry(&block)
  159. # - #mkdir(*args)
  160. # - #opendir(*args)
  161. #
  162. # === IO
  163. #
  164. # These methods are a facade for IO:
  165. # - #each_line(*args, &block)
  166. # - #read(*args)
  167. # - #readlines(*args)
  168. # - #sysopen(*args)
  169. #
  170. # === Utilities
  171. #
  172. # These methods are a mixture of Find, FileUtils, and others:
  173. # - #find(&block)
  174. # - #mkpath
  175. # - #rmtree
  176. # - #unlink / #delete
  177. #
  178. #
  179. # == Method documentation
  180. #
  181. # As the above section shows, most of the methods in Pathname are facades.  The
  182. # documentation for these methods generally just says, for instance, "See
  183. # FileTest.writable?", as you should be familiar with the original method
  184. # anyway, and its documentation (e.g. through +ri+) will contain more
  185. # information.  In some cases, a brief description will follow.
  186. #
  187. class Pathname
  188.  
  189.   # :stopdoc:
  190.   if RUBY_VERSION < "1.9"
  191.     TO_PATH = :to_str
  192.   else
  193.     # to_path is implemented so Pathname objects are usable with File.open, etc.
  194.     TO_PATH = :to_path
  195.   end
  196.   # :startdoc:
  197.  
  198.   #
  199.   # Create a Pathname object from the given String (or String-like object).
  200.   # If +path+ contains a NUL character (<tt>\0</tt>), an ArgumentError is raised.
  201.   #
  202.   def initialize(path)
  203.     path = path.__send__(TO_PATH) if path.respond_to? TO_PATH
  204.     @path = path.dup
  205.  
  206.     if /\0/ =~ @path
  207.       raise ArgumentError, "pathname contains \\0: #{@path.inspect}"
  208.     end
  209.  
  210.     self.taint if @path.tainted?
  211.   end
  212.  
  213.   def freeze() super; @path.freeze; self end
  214.   def taint() super; @path.taint; self end
  215.   def untaint() super; @path.untaint; self end
  216.  
  217.   #
  218.   # Compare this pathname with +other+.  The comparison is string-based.
  219.   # Be aware that two different paths (<tt>foo.txt</tt> and <tt>./foo.txt</tt>)
  220.   # can refer to the same file.
  221.   #
  222.   def ==(other)
  223.     return false unless Pathname === other
  224.     other.to_s == @path
  225.   end
  226.   alias === ==
  227.   alias eql? ==
  228.  
  229.   # Provides for comparing pathnames, case-sensitively.
  230.   def <=>(other)
  231.     return nil unless Pathname === other
  232.     @path.tr('/', "\0") <=> other.to_s.tr('/', "\0")
  233.   end
  234.  
  235.   def hash # :nodoc:
  236.     @path.hash
  237.   end
  238.  
  239.   # Return the path as a String.
  240.   def to_s
  241.     @path.dup
  242.   end
  243.  
  244.   # to_path is implemented so Pathname objects are usable with File.open, etc.
  245.   alias_method TO_PATH, :to_s
  246.  
  247.   def inspect # :nodoc:
  248.     "#<#{self.class}:#{@path}>"
  249.   end
  250.  
  251.   # Return a pathname which is substituted by String#sub.
  252.   def sub(pattern, *rest, &block)
  253.     if block
  254.       path = @path.sub(pattern, *rest) {|*args|
  255.         begin
  256.           old = Thread.current[:pathname_sub_matchdata]
  257.           Thread.current[:pathname_sub_matchdata] = $~
  258.           eval("$~ = Thread.current[:pathname_sub_matchdata]", block.binding)
  259.         ensure
  260.           Thread.current[:pathname_sub_matchdata] = old
  261.         end
  262.         yield(*args)
  263.       }
  264.     else
  265.       path = @path.sub(pattern, *rest)
  266.     end
  267.     self.class.new(path)
  268.   end
  269.  
  270.   if File::ALT_SEPARATOR
  271.     SEPARATOR_PAT = /[#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}]/
  272.   else
  273.     SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
  274.   end
  275.  
  276.   # chop_basename(path) -> [pre-basename, basename] or nil
  277.   def chop_basename(path)
  278.     base = File.basename(path)
  279.     if /\A#{SEPARATOR_PAT}?\z/ =~ base
  280.       return nil
  281.     else
  282.       return path[0, path.rindex(base)], base
  283.     end
  284.   end
  285.   private :chop_basename
  286.  
  287.   # split_names(path) -> prefix, [name, ...]
  288.   def split_names(path)
  289.     names = []
  290.     while r = chop_basename(path)
  291.       path, basename = r
  292.       names.unshift basename
  293.     end
  294.     return path, names
  295.   end
  296.   private :split_names
  297.  
  298.   def prepend_prefix(prefix, relpath)
  299.     if relpath.empty?
  300.       File.dirname(prefix)
  301.     elsif /#{SEPARATOR_PAT}/ =~ prefix
  302.       prefix = File.dirname(prefix)
  303.       prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a'
  304.       prefix + relpath
  305.     else
  306.       prefix + relpath
  307.     end
  308.   end
  309.   private :prepend_prefix
  310.  
  311.   # Returns clean pathname of +self+ with consecutive slashes and useless dots
  312.   # removed.  The filesystem is not accessed.
  313.   #
  314.   # If +consider_symlink+ is +true+, then a more conservative algorithm is used
  315.   # to avoid breaking symbolic linkages.  This may retain more <tt>..</tt>
  316.   # entries than absolutely necessary, but without accessing the filesystem,
  317.   # this can't be avoided.  See #realpath.
  318.   #
  319.   def cleanpath(consider_symlink=false)
  320.     if consider_symlink
  321.       cleanpath_conservative
  322.     else
  323.       cleanpath_aggressive
  324.     end
  325.   end
  326.  
  327.   #
  328.   # Clean the path simply by resolving and removing excess "." and ".." entries.
  329.   # Nothing more, nothing less.
  330.   #
  331.   def cleanpath_aggressive
  332.     path = @path
  333.     names = []
  334.     pre = path
  335.     while r = chop_basename(pre)
  336.       pre, base = r
  337.       case base
  338.       when '.'
  339.       when '..'
  340.         names.unshift base
  341.       else
  342.         if names[0] == '..'
  343.           names.shift
  344.         else
  345.           names.unshift base
  346.         end
  347.       end
  348.     end
  349.     if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
  350.       names.shift while names[0] == '..'
  351.     end
  352.     self.class.new(prepend_prefix(pre, File.join(*names)))
  353.   end
  354.   private :cleanpath_aggressive
  355.  
  356.   # has_trailing_separator?(path) -> bool
  357.   def has_trailing_separator?(path)
  358.     if r = chop_basename(path)
  359.       pre, basename = r
  360.       pre.length + basename.length < path.length
  361.     else
  362.       false
  363.     end
  364.   end
  365.   private :has_trailing_separator?
  366.  
  367.   # add_trailing_separator(path) -> path
  368.   def add_trailing_separator(path)
  369.     if File.basename(path + 'a') == 'a'
  370.       path
  371.     else
  372.       File.join(path, "") # xxx: Is File.join is appropriate to add separator?
  373.     end
  374.   end
  375.   private :add_trailing_separator
  376.  
  377.   def del_trailing_separator(path)
  378.     if r = chop_basename(path)
  379.       pre, basename = r
  380.       pre + basename
  381.     elsif /#{SEPARATOR_PAT}+\z/o =~ path
  382.       $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o]
  383.     else
  384.       path
  385.     end
  386.   end
  387.   private :del_trailing_separator
  388.  
  389.   def cleanpath_conservative
  390.     path = @path
  391.     names = []
  392.     pre = path
  393.     while r = chop_basename(pre)
  394.       pre, base = r
  395.       names.unshift base if base != '.'
  396.     end
  397.     if /#{SEPARATOR_PAT}/o =~ File.basename(pre)
  398.       names.shift while names[0] == '..'
  399.     end
  400.     if names.empty?
  401.       self.class.new(File.dirname(pre))
  402.     else
  403.       if names.last != '..' && File.basename(path) == '.'
  404.         names << '.'
  405.       end
  406.       result = prepend_prefix(pre, File.join(*names))
  407.       if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path)
  408.         self.class.new(add_trailing_separator(result))
  409.       else
  410.         self.class.new(result)
  411.       end
  412.     end
  413.   end
  414.   private :cleanpath_conservative
  415.  
  416.   def realpath_rec(prefix, unresolved, h)
  417.     resolved = []
  418.     until unresolved.empty?
  419.       n = unresolved.shift
  420.       if n == '.'
  421.         next
  422.       elsif n == '..'
  423.         resolved.pop
  424.       else
  425.         path = prepend_prefix(prefix, File.join(*(resolved + [n])))
  426.         if h.include? path
  427.           if h[path] == :resolving
  428.             raise Errno::ELOOP.new(path)
  429.           else
  430.             prefix, *resolved = h[path]
  431.           end
  432.         else
  433.           s = File.lstat(path)
  434.           if s.symlink?
  435.             h[path] = :resolving
  436.             link_prefix, link_names = split_names(File.readlink(path))
  437.             if link_prefix == ''
  438.               prefix, *resolved = h[path] = realpath_rec(prefix, resolved + link_names, h)
  439.             else
  440.               prefix, *resolved = h[path] = realpath_rec(link_prefix, link_names, h)
  441.             end
  442.           else
  443.             resolved << n
  444.             h[path] = [prefix, *resolved]
  445.           end
  446.         end
  447.       end
  448.     end
  449.     return prefix, *resolved
  450.   end
  451.   private :realpath_rec
  452.  
  453.   #
  454.   # Returns a real (absolute) pathname of +self+ in the actual filesystem.
  455.   # The real pathname doesn't contain symlinks or useless dots.
  456.   #
  457.   # No arguments should be given; the old behaviour is *obsoleted*. 
  458.   #
  459.   def realpath
  460.     path = @path
  461.     prefix, names = split_names(path)
  462.     if prefix == ''
  463.       prefix, names2 = split_names(Dir.pwd)
  464.       names = names2 + names
  465.     end
  466.     prefix, *names = realpath_rec(prefix, names, {})
  467.     self.class.new(prepend_prefix(prefix, File.join(*names)))
  468.   end
  469.  
  470.   # #parent returns the parent directory.
  471.   #
  472.   # This is same as <tt>self + '..'</tt>.
  473.   def parent
  474.     self + '..'
  475.   end
  476.  
  477.   # #mountpoint? returns +true+ if <tt>self</tt> points to a mountpoint.
  478.   def mountpoint?
  479.     begin
  480.       stat1 = self.lstat
  481.       stat2 = self.parent.lstat
  482.       stat1.dev == stat2.dev && stat1.ino == stat2.ino ||
  483.         stat1.dev != stat2.dev
  484.     rescue Errno::ENOENT
  485.       false
  486.     end
  487.   end
  488.  
  489.   #
  490.   # #root? is a predicate for root directories.  I.e. it returns +true+ if the
  491.   # pathname consists of consecutive slashes.
  492.   #
  493.   # It doesn't access actual filesystem.  So it may return +false+ for some
  494.   # pathnames which points to roots such as <tt>/usr/..</tt>.
  495.   #
  496.   def root?
  497.     !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path)
  498.   end
  499.  
  500.   # Predicate method for testing whether a path is absolute.
  501.   # It returns +true+ if the pathname begins with a slash.
  502.   def absolute?
  503.     !relative?
  504.   end
  505.  
  506.   # The opposite of #absolute?
  507.   def relative?
  508.     path = @path
  509.     while r = chop_basename(path)
  510.       path, basename = r
  511.     end
  512.     path == ''
  513.   end
  514.  
  515.   #
  516.   # Iterates over each component of the path.
  517.   #
  518.   #   Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
  519.   #     # yields "usr", "bin", and "ruby".
  520.   #
  521.   def each_filename # :yield: filename
  522.     prefix, names = split_names(@path)
  523.     names.each {|filename| yield filename }
  524.     nil
  525.   end
  526.  
  527.   # Iterates over and yields a new Pathname object
  528.   # for each element in the given path in descending order.
  529.   #
  530.   #  Pathname.new('/path/to/some/file.rb').descend {|v| p v}
  531.   #     #<Pathname:/>
  532.   #     #<Pathname:/path>
  533.   #     #<Pathname:/path/to>
  534.   #     #<Pathname:/path/to/some>
  535.   #     #<Pathname:/path/to/some/file.rb>
  536.   #
  537.   #  Pathname.new('path/to/some/file.rb').descend {|v| p v}
  538.   #     #<Pathname:path>
  539.   #     #<Pathname:path/to>
  540.   #     #<Pathname:path/to/some>
  541.   #     #<Pathname:path/to/some/file.rb>
  542.   #
  543.   # It doesn't access actual filesystem.
  544.   #
  545.   # This method is available since 1.8.5.
  546.   #
  547.   def descend
  548.     vs = []
  549.     ascend {|v| vs << v }
  550.     vs.reverse_each {|v| yield v }
  551.     nil
  552.   end
  553.  
  554.   # Iterates over and yields a new Pathname object
  555.   # for each element in the given path in ascending order.
  556.   #
  557.   #  Pathname.new('/path/to/some/file.rb').ascend {|v| p v}
  558.   #     #<Pathname:/path/to/some/file.rb>
  559.   #     #<Pathname:/path/to/some>
  560.   #     #<Pathname:/path/to>
  561.   #     #<Pathname:/path>
  562.   #     #<Pathname:/>
  563.   #
  564.   #  Pathname.new('path/to/some/file.rb').ascend {|v| p v}
  565.   #     #<Pathname:path/to/some/file.rb>
  566.   #     #<Pathname:path/to/some>
  567.   #     #<Pathname:path/to>
  568.   #     #<Pathname:path>
  569.   #
  570.   # It doesn't access actual filesystem.
  571.   #
  572.   # This method is available since 1.8.5.
  573.   #
  574.   def ascend
  575.     path = @path
  576.     yield self
  577.     while r = chop_basename(path)
  578.       path, name = r
  579.       break if path.empty?
  580.       yield self.class.new(del_trailing_separator(path))
  581.     end
  582.   end
  583.  
  584.   #
  585.   # Pathname#+ appends a pathname fragment to this one to produce a new Pathname
  586.   # object.
  587.   #
  588.   #   p1 = Pathname.new("/usr")      # Pathname:/usr
  589.   #   p2 = p1 + "bin/ruby"           # Pathname:/usr/bin/ruby
  590.   #   p3 = p1 + "/etc/passwd"        # Pathname:/etc/passwd
  591.   #
  592.   # This method doesn't access the file system; it is pure string manipulation. 
  593.   #
  594.   def +(other)
  595.     other = Pathname.new(other) unless Pathname === other
  596.     Pathname.new(plus(@path, other.to_s))
  597.   end
  598.  
  599.   def plus(path1, path2) # -> path
  600.     prefix2 = path2
  601.     index_list2 = []
  602.     basename_list2 = []
  603.     while r2 = chop_basename(prefix2)
  604.       prefix2, basename2 = r2
  605.       index_list2.unshift prefix2.length
  606.       basename_list2.unshift basename2
  607.     end
  608.     return path2 if prefix2 != ''
  609.     prefix1 = path1
  610.     while true
  611.       while !basename_list2.empty? && basename_list2.first == '.'
  612.         index_list2.shift
  613.         basename_list2.shift
  614.       end
  615.       break unless r1 = chop_basename(prefix1)
  616.       prefix1, basename1 = r1
  617.       next if basename1 == '.'
  618.       if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..'
  619.         prefix1 = prefix1 + basename1
  620.         break
  621.       end
  622.       index_list2.shift
  623.       basename_list2.shift
  624.     end
  625.     r1 = chop_basename(prefix1)
  626.     if !r1 && /#{SEPARATOR_PAT}/o =~ File.basename(prefix1)
  627.       while !basename_list2.empty? && basename_list2.first == '..'
  628.         index_list2.shift
  629.         basename_list2.shift
  630.       end
  631.     end
  632.     if !basename_list2.empty?
  633.       suffix2 = path2[index_list2.first..-1]
  634.       r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2
  635.     else
  636.       r1 ? prefix1 : File.dirname(prefix1)
  637.     end
  638.   end
  639.   private :plus
  640.  
  641.   #
  642.   # Pathname#join joins pathnames.
  643.   #
  644.   # <tt>path0.join(path1, ..., pathN)</tt> is the same as
  645.   # <tt>path0 + path1 + ... + pathN</tt>.
  646.   #
  647.   def join(*args)
  648.     args.unshift self
  649.     result = args.pop
  650.     result = Pathname.new(result) unless Pathname === result
  651.     return result if result.absolute?
  652.     args.reverse_each {|arg|
  653.       arg = Pathname.new(arg) unless Pathname === arg
  654.       result = arg + result
  655.       return result if result.absolute?
  656.     }
  657.     result
  658.   end
  659.  
  660.   #
  661.   # Returns the children of the directory (files and subdirectories, not
  662.   # recursive) as an array of Pathname objects.  By default, the returned
  663.   # pathnames will have enough information to access the files.  If you set
  664.   # +with_directory+ to +false+, then the returned pathnames will contain the
  665.   # filename only.
  666.   #
  667.   # For example:
  668.   #   p = Pathname("/usr/lib/ruby/1.8")
  669.   #   p.children
  670.   #       # -> [ Pathname:/usr/lib/ruby/1.8/English.rb,
  671.   #              Pathname:/usr/lib/ruby/1.8/Env.rb,
  672.   #              Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ]
  673.   #   p.children(false)
  674.   #       # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ]
  675.   #
  676.   # Note that the result never contain the entries <tt>.</tt> and <tt>..</tt> in
  677.   # the directory because they are not children.
  678.   #
  679.   # This method has existed since 1.8.1.
  680.   #
  681.   def children(with_directory=true)
  682.     with_directory = false if @path == '.'
  683.     result = []
  684.     Dir.foreach(@path) {|e|
  685.       next if e == '.' || e == '..'
  686.       if with_directory
  687.         result << self.class.new(File.join(@path, e))
  688.       else
  689.         result << self.class.new(e)
  690.       end
  691.     }
  692.     result
  693.   end
  694.  
  695.   #
  696.   # #relative_path_from returns a relative path from the argument to the
  697.   # receiver.  If +self+ is absolute, the argument must be absolute too.  If
  698.   # +self+ is relative, the argument must be relative too.
  699.   #
  700.   # #relative_path_from doesn't access the filesystem.  It assumes no symlinks.
  701.   #
  702.   # ArgumentError is raised when it cannot find a relative path.
  703.   #
  704.   # This method has existed since 1.8.1.
  705.   #
  706.   def relative_path_from(base_directory)
  707.     dest_directory = self.cleanpath.to_s
  708.     base_directory = base_directory.cleanpath.to_s
  709.     dest_prefix = dest_directory
  710.     dest_names = []
  711.     while r = chop_basename(dest_prefix)
  712.       dest_prefix, basename = r
  713.       dest_names.unshift basename if basename != '.'
  714.     end
  715.     base_prefix = base_directory
  716.     base_names = []
  717.     while r = chop_basename(base_prefix)
  718.       base_prefix, basename = r
  719.       base_names.unshift basename if basename != '.'
  720.     end
  721.     if dest_prefix != base_prefix
  722.       raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
  723.     end
  724.     while !dest_names.empty? &&
  725.           !base_names.empty? &&
  726.           dest_names.first == base_names.first
  727.       dest_names.shift
  728.       base_names.shift
  729.     end
  730.     if base_names.include? '..'
  731.       raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
  732.     end
  733.     base_names.fill('..')
  734.     relpath_names = base_names + dest_names
  735.     if relpath_names.empty?
  736.       Pathname.new('.')
  737.     else
  738.       Pathname.new(File.join(*relpath_names))
  739.     end
  740.   end
  741. end
  742.  
  743. class Pathname    # * IO *
  744.   #
  745.   # #each_line iterates over the line in the file.  It yields a String object
  746.   # for each line.
  747.   #
  748.   # This method has existed since 1.8.1.
  749.   #
  750.   def each_line(*args, &block) # :yield: line
  751.     IO.foreach(@path, *args, &block)
  752.   end
  753.  
  754.   # Pathname#foreachline is *obsoleted* at 1.8.1.  Use #each_line.
  755.   def foreachline(*args, &block)
  756.     warn "Pathname#foreachline is obsoleted.  Use Pathname#each_line."
  757.     each_line(*args, &block)
  758.   end
  759.  
  760.   # See <tt>IO.read</tt>.  Returns all the bytes from the file, or the first +N+
  761.   # if specified.
  762.   def read(*args) IO.read(@path, *args) end
  763.  
  764.   # See <tt>IO.readlines</tt>.  Returns all the lines from the file.
  765.   def readlines(*args) IO.readlines(@path, *args) end
  766.  
  767.   # See <tt>IO.sysopen</tt>.
  768.   def sysopen(*args) IO.sysopen(@path, *args) end
  769. end
  770.  
  771.  
  772. class Pathname    # * File *
  773.  
  774.   # See <tt>File.atime</tt>.  Returns last access time.
  775.   def atime() File.atime(@path) end
  776.  
  777.   # See <tt>File.ctime</tt>.  Returns last (directory entry, not file) change time.
  778.   def ctime() File.ctime(@path) end
  779.  
  780.   # See <tt>File.mtime</tt>.  Returns last modification time.
  781.   def mtime() File.mtime(@path) end
  782.  
  783.   # See <tt>File.chmod</tt>.  Changes permissions.
  784.   def chmod(mode) File.chmod(mode, @path) end
  785.  
  786.   # See <tt>File.lchmod</tt>.
  787.   def lchmod(mode) File.lchmod(mode, @path) end
  788.  
  789.   # See <tt>File.chown</tt>.  Change owner and group of file.
  790.   def chown(owner, group) File.chown(owner, group, @path) end
  791.  
  792.   # See <tt>File.lchown</tt>.
  793.   def lchown(owner, group) File.lchown(owner, group, @path) end
  794.  
  795.   # See <tt>File.fnmatch</tt>.  Return +true+ if the receiver matches the given
  796.   # pattern.
  797.   def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end
  798.  
  799.   # See <tt>File.fnmatch?</tt> (same as #fnmatch).
  800.   def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end
  801.  
  802.   # See <tt>File.ftype</tt>.  Returns "type" of file ("file", "directory",
  803.   # etc).
  804.   def ftype() File.ftype(@path) end
  805.  
  806.   # See <tt>File.link</tt>.  Creates a hard link.
  807.   def make_link(old) File.link(old, @path) end
  808.  
  809.   # See <tt>File.open</tt>.  Opens the file for reading or writing.
  810.   def open(*args, &block) # :yield: file
  811.     File.open(@path, *args, &block)
  812.   end
  813.  
  814.   # See <tt>File.readlink</tt>.  Read symbolic link.
  815.   def readlink() self.class.new(File.readlink(@path)) end
  816.  
  817.   # See <tt>File.rename</tt>.  Rename the file.
  818.   def rename(to) File.rename(@path, to) end
  819.  
  820.   # See <tt>File.stat</tt>.  Returns a <tt>File::Stat</tt> object.
  821.   def stat() File.stat(@path) end
  822.  
  823.   # See <tt>File.lstat</tt>.
  824.   def lstat() File.lstat(@path) end
  825.  
  826.   # See <tt>File.symlink</tt>.  Creates a symbolic link.
  827.   def make_symlink(old) File.symlink(old, @path) end
  828.  
  829.   # See <tt>File.truncate</tt>.  Truncate the file to +length+ bytes.
  830.   def truncate(length) File.truncate(@path, length) end
  831.  
  832.   # See <tt>File.utime</tt>.  Update the access and modification times.
  833.   def utime(atime, mtime) File.utime(atime, mtime, @path) end
  834.  
  835.   # See <tt>File.basename</tt>.  Returns the last component of the path.
  836.   def basename(*args) self.class.new(File.basename(@path, *args)) end
  837.  
  838.   # See <tt>File.dirname</tt>.  Returns all but the last component of the path.
  839.   def dirname() self.class.new(File.dirname(@path)) end
  840.  
  841.   # See <tt>File.extname</tt>.  Returns the file's extension.
  842.   def extname() File.extname(@path) end
  843.  
  844.   # See <tt>File.expand_path</tt>.
  845.   def expand_path(*args) self.class.new(File.expand_path(@path, *args)) end
  846.  
  847.   # See <tt>File.split</tt>.  Returns the #dirname and the #basename in an
  848.   # Array.
  849.   def split() File.split(@path).map {|f| self.class.new(f) } end
  850.  
  851.   # Pathname#link is confusing and *obsoleted* because the receiver/argument
  852.   # order is inverted to corresponding system call.
  853.   def link(old)
  854.     warn 'Pathname#link is obsoleted.  Use Pathname#make_link.'
  855.     File.link(old, @path)
  856.   end
  857.  
  858.   # Pathname#symlink is confusing and *obsoleted* because the receiver/argument
  859.   # order is inverted to corresponding system call.
  860.   def symlink(old)
  861.     warn 'Pathname#symlink is obsoleted.  Use Pathname#make_symlink.'
  862.     File.symlink(old, @path)
  863.   end
  864. end
  865.  
  866.  
  867. class Pathname    # * FileTest *
  868.  
  869.   # See <tt>FileTest.blockdev?</tt>.
  870.   def blockdev?() FileTest.blockdev?(@path) end
  871.  
  872.   # See <tt>FileTest.chardev?</tt>.
  873.   def chardev?() FileTest.chardev?(@path) end
  874.  
  875.   # See <tt>FileTest.executable?</tt>.
  876.   def executable?() FileTest.executable?(@path) end
  877.  
  878.   # See <tt>FileTest.executable_real?</tt>.
  879.   def executable_real?() FileTest.executable_real?(@path) end
  880.  
  881.   # See <tt>FileTest.exist?</tt>.
  882.   def exist?() FileTest.exist?(@path) end
  883.  
  884.   # See <tt>FileTest.grpowned?</tt>.
  885.   def grpowned?() FileTest.grpowned?(@path) end
  886.  
  887.   # See <tt>FileTest.directory?</tt>.
  888.   def directory?() FileTest.directory?(@path) end
  889.  
  890.   # See <tt>FileTest.file?</tt>.
  891.   def file?() FileTest.file?(@path) end
  892.  
  893.   # See <tt>FileTest.pipe?</tt>.
  894.   def pipe?() FileTest.pipe?(@path) end
  895.  
  896.   # See <tt>FileTest.socket?</tt>.
  897.   def socket?() FileTest.socket?(@path) end
  898.  
  899.   # See <tt>FileTest.owned?</tt>.
  900.   def owned?() FileTest.owned?(@path) end
  901.  
  902.   # See <tt>FileTest.readable?</tt>.
  903.   def readable?() FileTest.readable?(@path) end
  904.  
  905.   # See <tt>FileTest.world_readable?</tt>.
  906.   def world_readable?() FileTest.world_readable?(@path) end
  907.  
  908.   # See <tt>FileTest.readable_real?</tt>.
  909.   def readable_real?() FileTest.readable_real?(@path) end
  910.  
  911.   # See <tt>FileTest.setuid?</tt>.
  912.   def setuid?() FileTest.setuid?(@path) end
  913.  
  914.   # See <tt>FileTest.setgid?</tt>.
  915.   def setgid?() FileTest.setgid?(@path) end
  916.  
  917.   # See <tt>FileTest.size</tt>.
  918.   def size() FileTest.size(@path) end
  919.  
  920.   # See <tt>FileTest.size?</tt>.
  921.   def size?() FileTest.size?(@path) end
  922.  
  923.   # See <tt>FileTest.sticky?</tt>.
  924.   def sticky?() FileTest.sticky?(@path) end
  925.  
  926.   # See <tt>FileTest.symlink?</tt>.
  927.   def symlink?() FileTest.symlink?(@path) end
  928.  
  929.   # See <tt>FileTest.writable?</tt>.
  930.   def writable?() FileTest.writable?(@path) end
  931.  
  932.   # See <tt>FileTest.world_writable?</tt>.
  933.   def world_writable?() FileTest.world_writable?(@path) end
  934.  
  935.   # See <tt>FileTest.writable_real?</tt>.
  936.   def writable_real?() FileTest.writable_real?(@path) end
  937.  
  938.   # See <tt>FileTest.zero?</tt>.
  939.   def zero?() FileTest.zero?(@path) end
  940. end
  941.  
  942.  
  943. class Pathname    # * Dir *
  944.   # See <tt>Dir.glob</tt>.  Returns or yields Pathname objects.
  945.   def Pathname.glob(*args) # :yield: p
  946.     if block_given?
  947.       Dir.glob(*args) {|f| yield self.new(f) }
  948.     else
  949.       Dir.glob(*args).map {|f| self.new(f) }
  950.     end
  951.   end
  952.  
  953.   # See <tt>Dir.getwd</tt>.  Returns the current working directory as a Pathname.
  954.   def Pathname.getwd() self.new(Dir.getwd) end
  955.   class << self; alias pwd getwd end
  956.  
  957.   # Pathname#chdir is *obsoleted* at 1.8.1.
  958.   def chdir(&block)
  959.     warn "Pathname#chdir is obsoleted.  Use Dir.chdir."
  960.     Dir.chdir(@path, &block)
  961.   end
  962.  
  963.   # Pathname#chroot is *obsoleted* at 1.8.1.
  964.   def chroot
  965.     warn "Pathname#chroot is obsoleted.  Use Dir.chroot."
  966.     Dir.chroot(@path)
  967.   end
  968.  
  969.   # Return the entries (files and subdirectories) in the directory, each as a
  970.   # Pathname object.
  971.   def entries() Dir.entries(@path).map {|f| self.class.new(f) } end
  972.  
  973.   # Iterates over the entries (files and subdirectories) in the directory.  It
  974.   # yields a Pathname object for each entry.
  975.   #
  976.   # This method has existed since 1.8.1.
  977.   def each_entry(&block) # :yield: p
  978.     Dir.foreach(@path) {|f| yield self.class.new(f) }
  979.   end
  980.  
  981.   # Pathname#dir_foreach is *obsoleted* at 1.8.1.
  982.   def dir_foreach(*args, &block)
  983.     warn "Pathname#dir_foreach is obsoleted.  Use Pathname#each_entry."
  984.     each_entry(*args, &block)
  985.   end
  986.  
  987.   # See <tt>Dir.mkdir</tt>.  Create the referenced directory.
  988.   def mkdir(*args) Dir.mkdir(@path, *args) end
  989.  
  990.   # See <tt>Dir.rmdir</tt>.  Remove the referenced directory.
  991.   def rmdir() Dir.rmdir(@path) end
  992.  
  993.   # See <tt>Dir.open</tt>.
  994.   def opendir(&block) # :yield: dir
  995.     Dir.open(@path, &block)
  996.   end
  997. end
  998.  
  999.  
  1000. class Pathname    # * Find *
  1001.   #
  1002.   # Pathname#find is an iterator to traverse a directory tree in a depth first
  1003.   # manner.  It yields a Pathname for each file under "this" directory.
  1004.   #
  1005.   # Since it is implemented by <tt>find.rb</tt>, <tt>Find.prune</tt> can be used
  1006.   # to control the traverse.
  1007.   #
  1008.   # If +self+ is <tt>.</tt>, yielded pathnames begin with a filename in the
  1009.   # current directory, not <tt>./</tt>.
  1010.   #
  1011.   def find(&block) # :yield: p
  1012.     require 'find'
  1013.     if @path == '.'
  1014.       Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) }
  1015.     else
  1016.       Find.find(@path) {|f| yield self.class.new(f) }
  1017.     end
  1018.   end
  1019. end
  1020.  
  1021.  
  1022. class Pathname    # * FileUtils *
  1023.   # See <tt>FileUtils.mkpath</tt>.  Creates a full path, including any
  1024.   # intermediate directories that don't yet exist.
  1025.   def mkpath
  1026.     require 'fileutils'
  1027.     FileUtils.mkpath(@path)
  1028.     nil
  1029.   end
  1030.  
  1031.   # See <tt>FileUtils.rm_r</tt>.  Deletes a directory and all beneath it.
  1032.   def rmtree
  1033.     # The name "rmtree" is borrowed from File::Path of Perl.
  1034.     # File::Path provides "mkpath" and "rmtree".
  1035.     require 'fileutils'
  1036.     FileUtils.rm_r(@path)
  1037.     nil
  1038.   end
  1039. end
  1040.  
  1041.  
  1042. class Pathname    # * mixed *
  1043.   # Removes a file or directory, using <tt>File.unlink</tt> or
  1044.   # <tt>Dir.unlink</tt> as necessary.
  1045.   def unlink()
  1046.     begin
  1047.       Dir.unlink @path
  1048.     rescue Errno::ENOTDIR
  1049.       File.unlink @path
  1050.     end
  1051.   end
  1052.   alias delete unlink
  1053.  
  1054.   # This method is *obsoleted* at 1.8.1.  Use #each_line or #each_entry.
  1055.   def foreach(*args, &block)
  1056.     warn "Pathname#foreach is obsoleted.  Use each_line or each_entry."
  1057.     if FileTest.directory? @path
  1058.       # For polymorphism between Dir.foreach and IO.foreach,
  1059.       # Pathname#foreach doesn't yield Pathname object.
  1060.       Dir.foreach(@path, *args, &block)
  1061.     else
  1062.       IO.foreach(@path, *args, &block)
  1063.     end
  1064.   end
  1065. end
  1066.  
  1067. module Kernel
  1068.   # create a pathname object.
  1069.   #
  1070.   # This method is available since 1.8.5.
  1071.   def Pathname(path) # :doc:
  1072.     Pathname.new(path)
  1073.   end
  1074.   private :Pathname
  1075. end
  1076.